package com.ss.pj.sc03.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.ss.pj.sc01.pojo.User;
import com.ss.pj.sc01.service.UserService;
import com.ss.pj.sc01.web.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 只允许对添加了 @RefreshScope 或 @ConfigurationProperties 注解的 Bean 刷新配置，可以将更新的配置数据注入到 Bean 中
 * @author 叁昇
 * @create 2020-11-23-10:39
 */
@Slf4j
@Service
@RefreshScope
public class UserServiceImpl  implements UserService {
    // 获取自定义的用户信息, 更改配置动态刷新时, 会重新给 bean 注入新值
    @Value("${sp.user-service.users}")
    private String userJson;

    @Override
    public User getUser(Integer id) {
        log.info("users json string : "+userJson);

        List<User> list = JsonUtils.from(userJson, new TypeReference<List<User>>() {});
        for (User u : list) {
            if (u.getId().equals(id)) {
                return u;
            }
        }
        return new User(id, "name-"+id, "pwd-"+id);
    }

    @Override
    public void addScore(Integer id, Integer score) {
        //TODO 这里增加积分
        log.info("user "+id+" - 增加积分 "+score);
    }

}
